import React, {useEffect, useState} from "react"
import {Editor} from "react-draft-wysiwyg"//npm install --save react-draft-wysiwyg
import { convertToRaw } from 'draft-js';//npm install --save draft-js
import draftToHtml from 'draftjs-to-html'//npm install --save draftjs-to-html
import htmlToDraft from 'html-to-draftjs'
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import  {ContentState,EditorState} from "draft-js";
export default function NewsEditor (props){//富文本编辑器
    useEffect(()=>{//将content的内容转化为draft
        const html = props.content
        if(html===undefined) return
        const contentBlock = htmlToDraft(html);
        if (contentBlock) {
            const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
            const editorState = EditorState.createWithContent(contentState);
            setEditorState(editorState)
        }
    },[props.content])
    const[editorState,setEditorState]=useState("")
    return(
        <div>
            <Editor
                editorState={editorState}
                toolbarClassName="aaaaa"
                wrapperClassName="bbbbb"
                editorClassName="ccccc"
                onEditorStateChange={(editorState)=>setEditorState(editorState)}
                onBlur={()=>{
                    // console.log(editorState)过于复杂，根本不知道数据在哪里
                    //下面进行转化，转成html <p>we34yuy</p>
                    // console.log(draftToHtml(convertToRaw(editorState.getCurrentContent())))
                    props.getContext(draftToHtml(convertToRaw(editorState.getCurrentContent())))
                }}
            />
        {/*  editorState+ onEditorStateChange是配合使用的，使Editor成为受控组件
            当内容修改时，保存到状态中。
            失去焦点时，将状态转换成html
            子组件调用父组件传入的函数，进行子传父
         */}
        </div>
    )
}